package com.yupi.yuaicodemother.ai.model;

import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.time.LocalDate;

/**
 * 文件保存服务
 * 将 AI 生成的 9 个文件一次性写入本地：
 * index.html / style.css / script.js / controller.java / service.java
 * serviceImpl.java / vo.java / do.java / sql
 */
@Service
public class FileSaveService {

    private final String baseDir = "src/main/resources/generated/" + LocalDate.now();

    public void save(MultiFileCodeResult result) throws IOException {
        Path root = Paths.get(baseDir);
        Files.createDirectories(root);

        // 1. 网页三件套
        Files.writeString(root.resolve("index.html"),  result.getHtmlCode(),   StandardCharsets.UTF_8);
        Files.writeString(root.resolve("style.css"),   result.getCssCode(),    StandardCharsets.UTF_8);
        Files.writeString(root.resolve("script.js"),   result.getJsCode(),     StandardCharsets.UTF_8);

        // 2. Java 后端代码
        Files.writeString(root.resolve("controller.java"),  result.getController(),  StandardCharsets.UTF_8);
        Files.writeString(root.resolve("service.java"),     result.getService(),     StandardCharsets.UTF_8);
        Files.writeString(root.resolve("serviceImpl.java"), result.getServiceImpl(), StandardCharsets.UTF_8);
        Files.writeString(root.resolve("vo.java"),          result.getVo(),          StandardCharsets.UTF_8);
        Files.writeString(root.resolve("do.java"),          result.getDO(),          StandardCharsets.UTF_8);

        // 3. 数据库
        Files.writeString(root.resolve("sql.sql"),          result.getSql(),         StandardCharsets.UTF_8);

        // 4. 项目说明
        String readme = "# AI 生成项目\n\n" + result.getDescription();
        Files.writeString(root.resolve("README.md"), readme, StandardCharsets.UTF_8);
    }
}